package com.hxgz.filter;

import com.hxgz.util.JwtUtil;
import io.jsonwebtoken.Claims;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class JwtFilter extends HandlerInterceptorAdapter {

  @Autowired
  private JwtUtil jwtUtil;

  @Override
  public boolean preHandle(HttpServletRequest request,
      HttpServletResponse httpServletResponse, Object handler) {
    final String authorization = request.getHeader("Authorization");
    if (authorization != null && authorization.startsWith("Bearer")) {
      final String token = authorization.substring(7);
      Claims claims = jwtUtil.praseJwt(token);
      if (claims != null) {
        if ("work".equals(claims.get("roles"))) {
          request.setAttribute("admin_claims", claims);
        }
        if ("user".equals(claims.get("roles"))) {
          request.setAttribute("user_claims", claims);
        }
      }
    }
    return true;
  }
}
